package com.weblog.weblog.admin.utils;
import com.weblog.weblog.admin.config.MinioProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author gc
 * @date 2023年10月07日 21:03
 */
@Slf4j
@Component
public class MinioUtil {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;


    public String uploadFile(MultipartFile file) throws Exception {

        if (file == null || file.getSize() == 0){
            log.error("==> 上传文件异常：文件大小不能为空 ...");
            throw new RuntimeException("文件大小不能为空");
        }

        //文件名称
        String originalFileName = file.getOriginalFilename();
        //文件Content-Type
        String contentType = file.getContentType();
        //生成储存对象名称
        String key = UUID.randomUUID().toString().replace("-", "");
        //获取文件后缀
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        //拼接
        String objectName = String.format("%s%s", key, suffix);

        log.info("==> 开始文件上传至 Minio, ObjectName：{}",objectName);

        //上传
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(contentType)
                .build());

        //返回访问链接
        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), minioProperties.getBucketName(), objectName);
        log.info("==> 上传文件至 Minio 成功，访问路径: {}", url);
        return url;
    }


}
